<template>
  <div class="equipment-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="title-section">
        <h2 class="page-title">
          <el-icon class="title-icon"><Box /></el-icon>
          设备材料管理
          <el-tag v-if="projectData.project_name" type="primary" size="small" style="margin-left: 10px;">
            {{ projectData.project_name }}
          </el-tag>
        </h2>
        <p class="description">
          管理项目设备材料的合同、下单、入库、出库等全流程信息
          <span v-if="projectData.project_id" style="color: #e6a23c; font-weight: 500;">
            (项目编号: {{ projectData.project_id }})
          </span>
          <span v-if="projectData.project_type" style="color: #409eff; font-weight: 500; margin-left: 10px;">
            [项目类型: {{ projectData.project_type }}]
          </span>
        </p>
      </div>
      <div class="header-actions">
        <el-button v-if="canAdd" type="primary" @click="showAddDialog('contract')" class="create-btn">
          <el-icon><Plus /></el-icon>
          新增设备合同
        </el-button>
        <el-button v-if="canAdd" type="success" @click="showAddDialog('order')" class="create-btn">
          <el-icon><ShoppingCart /></el-icon>
          新增下单信息
        </el-button>
        <el-button v-if="canAdd" type="warning" @click="showAddDialog('inbound')" class="create-btn">
          <el-icon><Files /></el-icon>
          新增入库信息
        </el-button>
        <el-button v-if="canAdd" type="info" @click="showAddDialog('outbound')" class="create-btn">
          <el-icon><ShoppingTrolley /></el-icon>
          新增出库信息
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索设备名称、型号、供货单位..."
        class="search-input"
        clearable
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch" :icon="Search">
        搜索
      </el-button>
      <el-button @click="resetSearch" :icon="Refresh">
        重置
      </el-button>
      <el-button type="success" @click="exportData" :icon="Files">
        导出数据
      </el-button>
      <el-button type="warning" @click="refreshData" :icon="Refresh">
        刷新数据
      </el-button>
    </div>

    <!-- 数据概览卡片 -->
    <div class="overview-cards">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <div class="overview-card contract-card">
            <div class="card-icon">
              <el-icon><Box /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-number">{{ contractCount }}</div>
              <div class="card-label">设备合同</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <div class="overview-card order-card">
            <div class="card-icon">
              <el-icon><ShoppingCart /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-number">{{ orderCount }}</div>
              <div class="card-label">下单记录</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <div class="overview-card inbound-card">
            <div class="card-icon">
              <el-icon><Files /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-number">{{ inboundCount }}</div>
              <div class="card-label">入库记录</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <div class="overview-card outbound-card">
            <div class="card-icon">
              <el-icon><ShoppingTrolley /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-number">{{ outboundCount }}</div>
              <div class="card-label">出库记录</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 数据统计图表 -->
    <div class="statistics-section">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span class="card-title">库存状态分布</span>
              </div>
            </template>
            <div class="chart-container">
              <div class="stat-item">
                <div class="stat-number success">{{ getInStockCount() }}</div>
                <div class="stat-label">有库存设备</div>
              </div>
              <div class="stat-item">
                <div class="stat-number danger">{{ getOutOfStockCount() }}</div>
                <div class="stat-label">无库存设备</div>
              </div>
              <div class="stat-item">
                <div class="stat-number warning">{{ getLowStockCount() }}</div>
                <div class="stat-label">库存不足</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span class="card-title">设备类型统计</span>
              </div>
            </template>
            <div class="chart-container">
              <div class="type-stats">
                <div v-for="(count, type) in getEquipmentTypeStats()" :key="type" class="type-stat-item">
                  <span class="type-name">{{ type || '未知类型' }}</span>
                  <span class="type-count">{{ count }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 库存预警信息 -->
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-card class="warning-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span class="card-title">
                  <el-icon style="color: #e6a23c;"><View /></el-icon>
                  库存预警信息
                </span>
              </div>
            </template>
            <div class="warning-list">
              <div v-if="getLowStockItems().length === 0" class="no-warning">
                暂无库存预警信息
              </div>
              <div v-else v-for="item in getLowStockItems()" :key="item.equipment_name" class="warning-item">
                <el-tag type="warning" size="small">{{ item.equipment_name }}</el-tag>
                <span class="warning-text">库存不足，当前库存: {{ item.in_stock_quantity }}，建议及时补充</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 加载状态提示 -->
    <div v-if="loading" class="loading-overlay">
      <el-card class="loading-card">
        <div class="loading-content">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <p>正在加载数据，请稍候...</p>
        </div>
      </el-card>
    </div>

    <!-- 多表格展示区域 -->
    <div v-else class="tables-container">
      <!-- 设备合同表格 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon><Box /></el-icon>
              设备合同信息
            </span>
            <div class="header-actions">
              <el-select v-model="contractFilter" placeholder="筛选条件" size="small" style="width: 150px; margin-right: 10px;">
                <el-option label="全部" value="" />
                <el-option label="有库存" value="inStock" />
                <el-option label="无库存" value="outOfStock" />
              </el-select>
              <el-button v-if="canAdd" type="primary" size="small" @click="showAddDialog('contract')">
                <el-icon><Plus /></el-icon>
                新增合同
              </el-button>
            </div>
          </div>
        </template>
        <el-table 
          :data="filteredContractData || []" 
          border 
          stripe 
          style="width: 100%"
          v-loading="loading"
          empty-text="暂无设备合同数据"
          :max-height="400"
          highlight-current-row
          @row-click="handleRowClick"
          header-cell-class-name="table-header-cell"
          cell-class-name="table-body-cell"
        >
          <el-table-column prop="equipment_name" label="设备名称" min-width="200" show-overflow-tooltip />
          <el-table-column prop="equipment_type" label="设备型号" min-width="200" show-overflow-tooltip />
          <el-table-column prop="equipment_sumtype" label="设备单位" width="100" />
          <el-table-column prop="equipment_sum" label="合同数量" width="120" />
          <el-table-column prop="supplier" label="供货单位" min-width="180" show-overflow-tooltip />

          <el-table-column label="操作" width="180" fixed="right" v-if="hasPermission">
            <template #default="scope">
              <el-button size="small" type="info" @click="showEquipmentDetails(scope.row.id)">
                <el-icon><View /></el-icon>
                详情
              </el-button>
              <el-button size="small" type="primary" @click="editRow(scope.row, 'contract')">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button v-if="canDelete" size="small" type="danger" @click="deleteRow(scope.row, 'contract')">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 下单信息表格 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon><ShoppingCart /></el-icon>
              下单信息
            </span>
            <el-button v-if="canAdd" type="success" size="small" @click="showAddDialog('order')">
              <el-icon><Plus /></el-icon>
              新增下单
            </el-button>
          </div>
        </template>
        <el-table 
          :data="orderTableData || []" 
          border 
          stripe 
          style="width: 100%"
          v-loading="loading"
          empty-text="暂无下单数据"
          :max-height="400"
          highlight-current-row
          header-cell-class-name="table-header-cell"
          cell-class-name="table-body-cell"
        >
          <el-table-column prop="equipment_name" label="设备名称" min-width="200" show-overflow-tooltip />
          <el-table-column prop="equipment_type" label="设备型号" min-width="150" show-overflow-tooltip />
          <el-table-column prop="quantity" label="下单数量" width="120" />
          <el-table-column prop="Reqd_date" label="要求到货时间" width="140" />
          <el-table-column prop="purchaser" label="采购人" width="120" />
          <el-table-column label="关联合同" width="120" align="center">
            <template #default="scope">
              <el-tag 
                v-if="getEquipmentContractInfo(scope.row.equipment_id)"
                type="success" 
                size="small"
              >
                有合同
              </el-tag>
              <el-tag v-else type="danger" size="small">无合同</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="180" v-if="hasPermission">
            <template #default="scope">
              <el-button size="small" type="info" @click="showEquipmentDetails(scope.row.equipment_id)">
                <el-icon><View /></el-icon>
                详情
              </el-button>
              <el-button size="small" type="primary" @click="editRow(scope.row, 'order')">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button v-if="canDeleteOrder(scope.row)" size="small" type="danger" @click="deleteRow(scope.row, 'order')">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 入库信息表格 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon><Files /></el-icon>
              入库信息
            </span>
            <el-button v-if="canAdd" type="warning" size="small" @click="showAddDialog('inbound')">
              <el-icon><Plus /></el-icon>
              新增入库
            </el-button>
          </div>
        </template>
        <el-table 
          :data="inboundTableData || []" 
          border 
          stripe 
          style="width: 100%"
          v-loading="loading"
          empty-text="暂无入库数据"
          :max-height="400"
          highlight-current-row
          header-cell-class-name="table-header-cell"
          cell-class-name="table-body-cell"
        >
          <el-table-column prop="equipment_name" label="设备名称" min-width="200" show-overflow-tooltip />
          <el-table-column prop="equipment_type" label="设备型号" min-width="150" show-overflow-tooltip />
          <el-table-column label="入库时间" width="140">
            <template #default="scope">
              {{ formatToChinaTime(scope.row.in_date) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="入库数量" width="120" />
          <el-table-column prop="receiver" label="入库人员" width="120" />
          <el-table-column label="关联订单" width="120" align="center">
            <template #default="scope">
              <el-tag 
                v-if="getEquipmentOrderInfo(scope.row.equipment_id)"
                type="success" 
                size="small"
              >
                有订单
              </el-tag>
              <el-tag v-else type="danger" size="small">无订单</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="当前库存" width="120" align="center">
            <template #default="scope">
              <span :class="getInboundStockStatusClass(scope.row)">
                {{ getCurrentStockQuantity(scope.row) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="180" v-if="hasPermission">
            <template #default="scope">
              <el-button size="small" type="primary" @click="editRow(scope.row, 'inbound')">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button v-if="canDeleteInbound(scope.row)" size="small" type="danger" @click="deleteRow(scope.row, 'inbound')">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 出库信息表格 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon><ShoppingTrolley /></el-icon>
              出库信息
            </span>
            <el-button v-if="canAdd" type="info" size="small" @click="showAddDialog('outbound')">
              <el-icon><Plus /></el-icon>
              新增出库
            </el-button>
          </div>
        </template>
        <el-table 
          :data="outboundTableData || []" 
          border 
          stripe 
          style="width: 100%"
          v-loading="loading"
          empty-text="暂无出库数据"
          :max-height="400"
          highlight-current-row
          header-cell-class-name="table-header-cell"
          cell-class-name="table-body-cell"
        >
          <el-table-column prop="equipment_name" label="设备名称" min-width="200" show-overflow-tooltip />
          <el-table-column label="出库时间" width="140">
            <template #default="scope">
              {{ formatToChinaTime(scope.row.out_date) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="出库数量" width="120" />
          <el-table-column prop="recipient" label="出库人员" width="120" />
          <el-table-column prop="usage" label="出库地点" min-width="140" show-overflow-tooltip />
          <el-table-column label="剩余库存" width="120" align="center">
            <template #default="scope">
              <span :class="getOutboundStockStatusClass(scope.row)">
                {{ getCurrentStockQuantity(scope.row) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="180" show-overflow-tooltip />
          <el-table-column label="操作" width="180" v-if="hasPermission">
            <template #default="scope">
              <el-button size="small" type="info" @click="showEquipmentDetails(scope.row.equipment_id)">
                <el-icon><View /></el-icon>
                详情
              </el-button>
              <el-button size="small" type="primary" @click="editRow(scope.row, 'outbound')">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button v-if="canDeleteOutbound(scope.row)" size="small" type="danger" @click="deleteRow(scope.row, 'outbound')">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 库存汇总表格 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon><View /></el-icon>
              库存汇总
            </span>
          </div>
        </template>
        <el-table 
          :data="inventoryTableData || []" 
          border 
          stripe 
          style="width: 100%"
          v-loading="loading"
          empty-text="暂无库存数据"
          :max-height="400"
          highlight-current-row
          header-cell-class-name="table-header-cell"
          cell-class-name="table-body-cell"
        >
          <el-table-column prop="equipment_name" label="设备名称" min-width="200" show-overflow-tooltip />
          <el-table-column prop="equipment_type" label="设备型号" min-width="180" show-overflow-tooltip />
          <el-table-column prop="total_quantity" label="合同数量" width="120" />
          <el-table-column prop="inbound_quantity" label="入库数量" width="120" />
          <el-table-column prop="outbound_quantity" label="出库数量" width="120" />
          <el-table-column prop="in_stock_quantity" label="在库数量" width="120">
            <template #default="scope">
              <span :class="getInventoryStockStatusClass(scope.row)">
                {{ scope.row.in_stock_quantity }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="库存状态" width="120" align="center">
            <template #default="scope">
              <el-tag 
                :type="getInventoryStockStatusType(scope.row)"
                size="small"
              >
                {{ getInventoryStockStatusText(scope.row) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作建议" min-width="150" show-overflow-tooltip>
            <template #default="scope">
              <span class="operation-suggestion">{{ getOperationSuggestion(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="关联状态" width="120" align="center">
            <template #default="scope">
              <el-button 
                size="small" 
                type="info" 
                @click="showEquipmentDetails(scope.row.equipment_id || scope.row.id)"
                :disabled="!scope.row.equipment_id && !scope.row.id"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="formData" :rules="getFormRules()" label-width="120px">
        <!-- 设备合同信息 -->
        <div v-if="currentDialogType === 'contract'" class="form-section">
          <h3>设备合同信息</h3>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="项目编号" prop="project_id">
                <el-input v-model="formData.project_id" placeholder="请输入项目编号" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="设备名称" prop="equipment_name">
                <el-input v-model="formData.equipment_name" placeholder="请输入设备名称" :disabled="currentRow && currentRow.id" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="设备类型" prop="equipment_type">
                <el-input v-model="formData.equipment_type" placeholder="请输入设备类型" :disabled="currentRow && currentRow.id" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="数量单位" prop="equipment_sumtype">
                <el-input v-model="formData.equipment_sumtype" placeholder="请输入数量单位" :disabled="currentRow && currentRow.id" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="合同数量" prop="equipment_sum">
                <el-input-number v-model="formData.equipment_sum" :min="0"  />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="供应商" prop="supplier">
                <el-input v-model="formData.supplier" placeholder="请输入供应商" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" :rows="3" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 订单信息 -->
        <div v-if="currentDialogType === 'order'" class="form-section">
          <h3>订单信息</h3>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="项目编号" prop="project_id">
                <el-input v-model="formData.project_id" placeholder="请输入项目编号" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="关联设备" prop="equipment_id">
                <el-select v-model="formData.equipment_id" placeholder="请选择设备"  @change="handleEquipmentChange" :disabled="currentRow && currentRow.id">
                  <el-option
                    v-for="equipment in equipmentList"
                    :key="equipment.id"
                    :label="`${equipment.equipment_name} (${equipment.equipment_type})`"
                    :value="equipment.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="要求到货时间" prop="Reqd_date">
                <el-date-picker
                  v-model="formData.Reqd_date"
                  type="date"
                  placeholder="选择日期"
                 
                  :disabled="currentRow && currentRow.id"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="下单数量" prop="quantity">
                <el-input-number v-model="formData.quantity" :min="0" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="采购人" prop="purchaser">
                <el-input v-model="formData.purchaser" placeholder="请输入采购人" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" :rows="3" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 入库信息 -->
        <div v-if="currentDialogType === 'inbound'" class="form-section">
          <h3>入库信息</h3>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="项目编号" prop="project_id">
                <el-input v-model="formData.project_id" placeholder="请输入项目编号" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="关联设备" prop="equipment_id">
                <el-select v-model="formData.equipment_id" placeholder="请选择设备"  @change="handleEquipmentChange" :disabled="currentRow && currentRow.id">
                  <el-option
                    v-for="equipment in equipmentList"
                    :key="equipment.id"
                    :label="`${equipment.equipment_name} (${equipment.equipment_type})`"
                    :value="equipment.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="入库时间" prop="in_date">
                <el-date-picker
                  v-model="formData.in_date"
                  type="date"
                  placeholder="选择日期"
                 
                  :disabled="currentRow && currentRow.id"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="入库数量" prop="quantity">
                <el-input-number v-model="formData.quantity" :min="0"  />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="入库地点" prop="in_location">
                <el-input v-model="formData.in_location" placeholder="请输入入库地点" :disabled="currentRow && currentRow.id" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="入库人员" prop="receiver">
                <el-input v-model="formData.receiver" placeholder="请输入入库人员" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" :rows="3" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 出库信息 -->
        <div v-if="currentDialogType === 'outbound'" class="form-section">
          <h3>出库信息</h3>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="项目编号" prop="project_id">
                <el-input v-model="formData.project_id" placeholder="请输入项目编号" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="关联设备" prop="equipment_id">
                <el-select 
                  v-model="formData.equipment_id" 
                  placeholder="请选择设备" 
                
                  @change="handleEquipmentChange"
                  :disabled="currentRow && currentRow.id"
                >
                  <el-option
                    v-for="equipment in equipmentList"
                    :key="equipment.id"
                    :label="`${equipment.equipment_name} (${equipment.equipment_type})`"
                    :value="equipment.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="出库时间" prop="out_date">
                <el-date-picker
                  v-model="formData.out_date"
                  type="date"
                  placeholder="选择日期"
                  
                  :disabled="currentRow && currentRow.id"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="出库数量" prop="quantity">
                <el-input-number v-model="formData.quantity" :min="0" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="出库地点" prop="usage">
                <el-input v-model="formData.usage" placeholder="请输入出库地点" :disabled="currentRow && currentRow.id" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="出库人员" prop="shipper">
                <el-input v-model="formData.shipper" placeholder="请输入出库人员" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" :rows="3" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Box, Plus, ShoppingCart, Files, Search, Edit, Delete, View, Refresh, Loading,ShoppingTrolley
} from '@element-plus/icons-vue'
import {
  getProjectEquipmentManagementList,
  createProjectEquipmentManagement,
  updateProjectEquipmentManagement,
  deleteProjectEquipmentManagement,
  getProjectEquipmentOrderList,
  createProjectEquipmentOrder,
  updateProjectEquipmentOrder,
  deleteProjectEquipmentOrder,
  getProjectEquipmentInboundList,
  createProjectEquipmentInbound,
  updateProjectEquipmentInbound,
  deleteProjectEquipmentInbound,
  getProjectEquipmentOutboundList,
  createProjectEquipmentOutbound,
  updateProjectEquipmentOutbound,
  deleteProjectEquipmentOutbound
} from '@/api/Projectequipmentmanagement.js'

// 定义props
const props = defineProps({
  projectId: {
    type: String,
    default: ''
  },
  projectData: {
    type: Object,
    default: () => ({})
  }
})

// 获取当前登录用户信息
const currentUser = ref(JSON.parse(localStorage.getItem('user') || '{}'))

// 检查是否为管理员
const isAdmin = computed(() => currentUser.value.userType === '管理员')

// 检查是否为当前项目的项目经理
const isProjectManager = computed(() => {
  if (!props.projectData || !props.projectData.project_manager) {
    return false
  }
  // 检查当前用户是否为该项目的项目经理
  return currentUser.value.username === props.projectData.project_manager || 
         currentUser.value.userId === props.projectData.project_manager ||
         currentUser.value.id === props.projectData.project_manager
})

// 检查是否有权限操作（只有当前项目的项目经理可以操作）
const hasPermission = computed(() => {
  return isProjectManager.value
})

// 检查是否可以新增（只有当前项目的项目经理可以新增）
const canAdd = computed(() => {
  return isProjectManager.value
})

// 检查是否可以删除（只有当前项目的项目经理可以删除）
const canDelete = computed(() => {
  return isProjectManager.value
})

// 检查是否可以编辑（只有当前项目的项目经理可以编辑）
const canEdit = computed(() => {
  return isProjectManager.value
})

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const searchKeyword = ref('')
const dialogVisible = ref(false)
const currentDialogType = ref('')
const currentRow = ref(null)
const formRef = ref(null)

// 表格数据
const contractTableData = ref([])
const orderTableData = ref([])
const inboundTableData = ref([])
const outboundTableData = ref([])
const inventoryTableData = ref([])
const equipmentList = ref([])

// 统计数据
const contractCount = ref(0)
const orderCount = ref(0)
const inboundCount = ref(0)
const outboundCount = ref(0)

// 筛选变量
const contractFilter = ref('')
const orderFilter = ref('')
const inboundFilter = ref('')
const outboundFilter = ref('')

// 筛选后的表格数据
const filteredContractData = computed(() => {
  if (!contractFilter.value) return contractTableData.value
  
  return contractTableData.value.filter(item => {
    const inventoryItem = inventoryTableData.value.find(inv => inv.equipment_name === item.equipment_name)
    if (contractFilter.value === 'inStock') {
      return inventoryItem && inventoryItem.in_stock_quantity > 0
    } else if (contractFilter.value === 'outOfStock') {
      return !inventoryItem || inventoryItem.in_stock_quantity <= 0
    }
    return true
  })
})

const filteredOrderData = computed(() => {
  if (!orderFilter.value) return orderTableData.value
  return orderTableData.value
})

const filteredInboundData = computed(() => {
  if (!inboundFilter.value) return inboundTableData.value
  return inboundTableData.value
})

const filteredOutboundData = computed(() => {
  if (!outboundFilter.value) return outboundTableData.value
  return outboundTableData.value
})

// 表单数据
const formData = reactive({
  project_id: '',
  equipment_name: '',
  equipment_type: '',
  equipment_sumtype: '',
  equipment_sum: 0,
  supplier: '',
  equipment_id: '',
  quantity: 0,
  purchaser: '',
  Reqd_date: '',
  remark: '',
  in_date: '',
  receiver: '',
  out_date: '',
  shipper: '',
  work_location: '',
  recipient_unit: '',
  recipient_person: '',
  inbound_location: '',
  usage: '', // 出库地点/用途
  in_location: '', // 入库地点
  out_location: '' // 出库地点
})

// 表单验证规则
const formRules = {
  project_id: [{ required: true, message: '请输入项目编号', trigger: 'blur' }],
  equipment_name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  equipment_type: [{ required: true, message: '请输入设备型号', trigger: 'blur' }],
  equipment_sum: [{ required: true, message: '请输入设备数量', trigger: 'blur' }],
  supplier: [{ required: true, message: '请输入供货单位', trigger: 'blur' }]
}

// 动态表单验证规则 - 已更新为更完善的版本

// 计算属性
const dialogTitle = computed(() => {
  const isEdit = currentRow.value && currentRow.value.id
  const action = isEdit ? '编辑' : '新增'
  
  const titles = {
    contract: `${action}设备合同`,
    order: `${action}下单信息`,
    inbound: `${action}入库信息`,
    outbound: `${action}出库信息`
  }
  return titles[currentDialogType.value] || action
})

// 方法
const loadData = async () => {
  try {
    loading.value = true
    const currentProjectId = props.projectData.project_id || props.projectId
    if (!currentProjectId) return
    
    const params = {
      page: 1,
      pageSize: 100,
      where:{project_id: currentProjectId}
    }

    // 先加载设备合同信息
    const contractResponse = await getProjectEquipmentManagementList(params)
    const contractData = contractResponse.records || []
    contractTableData.value = contractData
    contractCount.value = contractData.length

    // 更新设备列表，确保包含必要的字段
    equipmentList.value = contractData.map(equipment => ({
      id: equipment.id,
      equipment_name: equipment.equipment_name,
      equipment_type: equipment.equipment_type,
      equipment_sumtype: equipment.equipment_sumtype,
      equipment_sum: equipment.equipment_sum,
      supplier: equipment.supplier
    }))

    // 加载下单信息，确保与设备正确关联
    const orderResponse = await getProjectEquipmentOrderList(params)
    const orderData = orderResponse.records || []
    orderTableData.value = orderData.map(order => {
      const contract = contractData.find(c => c.id === order.equipment_id)
      return {
        ...order,
        equipment_name: contract?.equipment_name || '未知设备',
        equipment_type: contract?.equipment_type || '',
        equipment_sumtype: contract?.equipment_sumtype || ''
      }
    })
    orderCount.value = orderData.length

    // 加载入库信息，确保与设备正确关联
    const inboundResponse = await getProjectEquipmentInboundList(params)
    const inboundData = inboundResponse.records || []
    inboundTableData.value = inboundData.map(inbound => {
      const contract = contractData.find(c => c.id === inbound.equipment_id)
      return {
        ...inbound,
        equipment_name: contract?.equipment_name || '未知设备',
        equipment_type: contract?.equipment_type || '',
        equipment_sumtype: contract?.equipment_sumtype || ''
      }
    })
    inboundCount.value = inboundData.length

    // 加载出库信息，确保与设备正确关联
    const outboundResponse = await getProjectEquipmentOutboundList(params)
    const outboundData = outboundResponse.records || []
    outboundTableData.value = outboundData.map(outbound => {
      const contract = contractData.find(c => c.id === outbound.equipment_id)
      return {
        ...outbound,
        equipment_name: contract?.equipment_name || '未知设备',
        equipment_type: contract?.equipment_type || '',
        equipment_sumtype: contract?.equipment_sumtype || ''
      }
    })
    outboundCount.value = outboundData.length

    // 生成库存汇总数据
    generateInventoryData(contractData, inboundData, outboundData)

  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 生成库存汇总数据
const generateInventoryData = (contracts, inbounds, outbounds) => {
  const inventoryMap = new Map()
  
  // 初始化合同数据
  contracts.forEach(contract => {
    inventoryMap.set(contract.id, {
      equipment_id: contract.id,
      equipment_name: contract.equipment_name,
      equipment_type: contract.equipment_type,
      total_quantity: Number(contract.equipment_sum) || 0,
      inbound_quantity: 0,
      outbound_quantity: 0,
      in_stock_quantity: 0
    })
  })
  
  // 累加入库数量
  inbounds.forEach(inbound => {
    if (inventoryMap.has(inbound.equipment_id)) {
      const item = inventoryMap.get(inbound.equipment_id)
      item.inbound_quantity += Number(inbound.quantity) || 0
    }
  })
  
  // 累加出库数量
  outbounds.forEach(outbound => {
    if (inventoryMap.has(outbound.equipment_id)) {
      const item = inventoryMap.get(outbound.equipment_id)
      item.outbound_quantity += Number(outbound.quantity) || 0
    }
  })
  
  // 计算在库数量
  inventoryMap.forEach(item => {
    item.in_stock_quantity = item.inbound_quantity - item.outbound_quantity
  })
  
  // 确保数据更新到响应式变量
  inventoryTableData.value = Array.from(inventoryMap.values())
  
  // 调试信息
  console.log('库存数据已更新:', inventoryTableData.value)
}

// 项目变更处理
const onProjectChange = () => {
  loadData()
}

// 搜索处理
const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    loadData()
    return
  }
  
  const keyword = searchKeyword.value.toLowerCase().trim()
  
  // 搜索设备合同
  const filteredContracts = contractTableData.value.filter(item => 
    item.equipment_name?.toLowerCase().includes(keyword) ||
    item.equipment_type?.toLowerCase().includes(keyword) ||
    item.supplier?.toLowerCase().includes(keyword)
  )
  
  // 搜索下单信息
  const filteredOrders = orderTableData.value.filter(item => 
    item.equipment_name?.toLowerCase().includes(keyword) ||
    item.purchaser?.toLowerCase().includes(keyword) ||
    item.remark?.toLowerCase().includes(keyword)
  )
  
  // 搜索入库信息
  const filteredInbounds = inboundTableData.value.filter(item => 
    item.equipment_name?.toLowerCase().includes(keyword) ||
    item.receiver?.toLowerCase().includes(keyword) ||
    item.remark?.toLowerCase().includes(keyword)
  )
  
  // 搜索出库信息
  const filteredOutbounds = outboundTableData.value.filter(item => 
    item.equipment_name?.toLowerCase().includes(keyword) ||
    item.shipper?.toLowerCase().includes(keyword) ||
    item.work_location?.toLowerCase().includes(keyword) ||
    item.recipient_unit?.toLowerCase().includes(keyword) ||
    item.recipient_person?.toLowerCase().includes(keyword) ||
    item.remark?.toLowerCase().includes(keyword)
  )
  
  // 更新表格数据
  contractTableData.value = filteredContracts
  orderTableData.value = filteredOrders
  inboundTableData.value = filteredInbounds
  outboundTableData.value = filteredOutbounds
  
  // 更新统计数据
  contractCount.value = filteredContracts.length
  orderCount.value = filteredOrders.length
  inboundCount.value = filteredInbounds.length
  outboundCount.value = filteredOutbounds.length
  
  // 重新生成库存汇总
  generateInventoryData(filteredContracts, filteredInbounds, filteredOutbounds)
  
  ElMessage.success(`搜索完成，找到 ${filteredContracts.length + filteredOrders.length + filteredInbounds.length + filteredOutbounds.length} 条相关记录`)
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  loadData()
}

// 行点击处理
const handleRowClick = (row) => {
  currentRow.value = row
}

const showAddDialog = (type) => {
  currentDialogType.value = type
  resetForm()
  dialogVisible.value = true
}

const resetForm = () => {
  // 保存当前项目ID
  const currentProjectId = props.projectData.project_id || props.projectId
  
  // 完全重置表单数据，避免引用现有数据
  Object.keys(formData).forEach(key => {
    if (key.includes('date')) {
      formData[key] = ''
    } else if (key.includes('quantity') || key.includes('price') || key.includes('sum')) {
      formData[key] = 0
    } else {
      formData[key] = ''
    }
  })
  
  // 重新设置项目ID，确保不会影响其他字段
  formData.project_id = currentProjectId
  
  // 清空当前行引用，确保是新增模式
  currentRow.value = null
}

const submitForm = async () => {
  try {
    await formRef.value.validate()
    
    // 使用新的设备操作验证逻辑
    let validationResult = { valid: true }
    
    switch (currentDialogType.value) {
      case 'order':
        validationResult = validateEquipmentOperation('order', formData.equipment_id, formData.quantity)
        break
      case 'inbound':
        validationResult = validateEquipmentOperation('inbound', formData.equipment_id, formData.quantity)
        break
      case 'outbound':
        validationResult = validateEquipmentOperation('outbound', formData.equipment_id, formData.quantity)
        break
    }
    
    if (!validationResult.valid) {
      ElMessage.error(validationResult.message)
      return
    }
    
    submitLoading.value = true
    let response
    
    // 创建新的数据对象，避免引用现有数据
    const submitData = { 
      project_id: props.projectData.project_id || props.projectId
    }
    
    // 根据对话框类型添加相应字段
    switch (currentDialogType.value) {
      case 'contract':
        Object.assign(submitData, {
          equipment_name: formData.equipment_name,
          equipment_type: formData.equipment_type,
          equipment_sumtype: formData.equipment_sumtype,
          equipment_sum: formData.equipment_sum,
          supplier: formData.supplier,
          remark: formData.remark
        })
        break
      case 'order':
        Object.assign(submitData, {
          equipment_id: formData.equipment_id,
          quantity: formData.quantity,
          Reqd_date: formData.Reqd_date,
          purchaser: formData.purchaser,
          remark: formData.remark
        })
        break
      case 'inbound':
        Object.assign(submitData, {
          equipment_id: formData.equipment_id,
          quantity: formData.quantity,
          in_date: formData.in_date,
          receiver: formData.receiver,
          remark: formData.remark || '',
          // 确保必填字段有值
          in_location: formData.in_location || '默认入库地点',
          usage: '入库' // 入库操作的用途标识
        })
        break
      case 'outbound':
        Object.assign(submitData, {
          equipment_id: formData.equipment_id,
          quantity: formData.quantity,
          out_date: formData.out_date,
          recipient: formData.recipient || '默认出库人员',
          usage: formData.usage || '默认出库地点', // 出库地点，必填字段
          remark: formData.remark || ''
        })
        break
    }
    
    // 判断是新增还是编辑
    const isEdit = currentRow.value && currentRow.value.id
    
    if (isEdit) {
      // 编辑模式 - 添加ID字段
      submitData.id = currentRow.value.id
      switch (currentDialogType.value) {
        case 'contract':
          response = await updateProjectEquipmentManagement(submitData.id, submitData)
          break
        case 'order':
          response = await updateProjectEquipmentOrder(submitData.id, submitData)
          break
        case 'inbound':
          response = await updateProjectEquipmentInbound(submitData.id, submitData)
          break
        case 'outbound':
          response = await updateProjectEquipmentOutbound(submitData.id, submitData)
          break
      }
    } else {
      // 新增模式
      switch (currentDialogType.value) {
        case 'contract':
          response = await createProjectEquipmentManagement(submitData)
          break
        case 'order':
          response = await createProjectEquipmentOrder(submitData)
          break
        case 'inbound':
          response = await createProjectEquipmentInbound(submitData)
          break
        case 'outbound':
          response = await createProjectEquipmentOutbound(submitData)
          break
      }
    }

    if (response) {
      ElMessage.success(isEdit ? '编辑成功' : '新增成功')
      dialogVisible.value = false
      resetForm()
      currentRow.value = null
      loadData()
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

const editRow = (row, type) => {
  if (!hasPermission.value) {
    ElMessage.warning('您没有编辑权限')
    return
  }

  currentRow.value = row
  currentDialogType.value = type
  
  // 重置表单
 // resetForm()
  
  // 根据类型填充不同的字段，使用深拷贝避免引用问题
  switch (type) {
    case 'contract':
      // 编辑设备合同时，显示当前订单使用情况
      const existingOrders = orderTableData.value.filter(o => o.equipment_id === row.id)
      const totalOrderedQuantity = existingOrders.reduce((sum, order) => sum + (Number(order.quantity) || 0), 0)
      
      if (totalOrderedQuantity > 0) {
        ElMessage.info(`该设备已有订单数量: ${totalOrderedQuantity}，当前合同数量: ${row.equipment_sum || 0}`)
        
        if (totalOrderedQuantity > (row.equipment_sum || 0)) {
          ElMessage.warning(`订单数量已超过合同数量，建议将合同数量调整为: ${totalOrderedQuantity}`)
        }
      }
      
      Object.assign(formData, {
        project_id: row.project_id || '',
        equipment_name: row.equipment_name || '',
        equipment_type: row.equipment_type || '',
        equipment_sumtype: row.equipment_sumtype || '',
        equipment_sum: row.equipment_sum || 0,
        supplier: row.supplier || '',
        remark: row.remark || ''
      })
      break
    case 'order':
      Object.assign(formData, {
        project_id: row.project_id || '',
        equipment_id: row.equipment_id || '',
        quantity: row.quantity || 0,
        Reqd_date: row.Reqd_date || '',
        purchaser: row.purchaser || '',
        remark: row.remark || ''
      })
      break
    case 'inbound':
      Object.assign(formData, {
        project_id: row.project_id || '',
        equipment_id: row.equipment_id || '',
        quantity: row.quantity || 0,
        in_date: row.in_date || '',
        inbound_location: row.inbound_location || '',
        receiver: row.receiver || '',
        remark: row.remark || ''
      })
      break
    case 'outbound':
      Object.assign(formData, {
        project_id: row.project_id || '',
        equipment_id: row.equipment_id || '',
        quantity: row.quantity || 0,
        out_date: row.out_date || '',
        recipient: row.recipient || '',
        usage: row.usage || '', // 出库地点
        remark: row.remark || ''
      })
      
      // 编辑出库时，显示当前库存信息
      const inventoryItem = inventoryTableData.value.find(item => 
        item.equipment_name === row.equipment_name
      )
      if (inventoryItem) {
        ElMessage.info(`该设备当前库存: ${inventoryItem.in_stock_quantity}，已出库: ${inventoryItem.outbound_quantity}`)
      }
      break
  }
  
  dialogVisible.value = true
}

// 改进的删除函数，添加更好的错误处理
const deleteRow = async (row, type) => {
  console.log('删除行数据:', row, '类型:', type)
  
  if (!canDelete.value) {
    ElMessage.warning('您没有删除权限')
    return
  }

  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    let response
    const recordId = row.id || row.record_id
    
    if (!recordId) {
      ElMessage.error('记录ID不存在，无法删除')
      return
    }

    switch (type) {
      case 'contract':
        response = await deleteProjectEquipmentManagement(recordId)
        break
      case 'order':
        response = await deleteProjectEquipmentOrder(recordId)
        break
      case 'inbound':
        response = await deleteProjectEquipmentInbound(recordId)
        break
      case 'outbound':
        response = await deleteProjectEquipmentOutbound(recordId)
        break
      default:
        ElMessage.error('未知的记录类型')
        return
    }

    // 改进响应处理逻辑
    if (response !== undefined && response !== null) {
      // 即使响应为空对象或false，也认为是成功
      ElMessage.success('删除成功')
      // 根据删除类型强制刷新特定数据
      setTimeout(() => {
        forceRefreshData(type)
      }, 500)
    } else {
      // 如果响应为undefined或null，可能是网络问题
      ElMessage.warning('删除操作可能未完成，请刷新页面确认')
      // 仍然尝试强制刷新特定数据
      setTimeout(() => {
        forceRefreshData(type)
      }, 1000)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      
      // 根据错误类型提供更友好的错误信息
      if (error.name === 'SyntaxError' && error.message.includes('JSON')) {
        ElMessage.error('服务器响应格式错误，请稍后重试')
      } else if (error.message && error.message.includes('fetch')) {
        ElMessage.error('网络连接失败，请检查网络后重试')
      } else if (error.message && error.message.includes('500')) {
        ElMessage.error('服务器内部错误，删除操作可能已完成，请刷新页面确认')
      } else if (error.message && error.message.includes('404')) {
        ElMessage.error('记录不存在或已被删除，请刷新页面')
      } else if (error.message) {
        ElMessage.error(`删除失败: ${error.message}`)
      } else {
        ElMessage.error('删除失败，请检查网络连接')
      }
      
      // 即使删除失败，也尝试强制刷新特定数据以确保界面同步
      setTimeout(() => {
        forceRefreshData(type)
      }, 1000)
    }
  }
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 刷新数据
const refreshData = () => {
  searchKeyword.value = ''
  loadData()
  ElMessage.success('数据已刷新')
}

// 强制刷新特定类型的数据
const forceRefreshData = async (type) => {
  try {
    const currentProjectId = props.projectData.project_id || props.projectId
    if (!currentProjectId) return
    
    const params = {
      page: 1,
      pageSize: 100,
      where: { project_id: currentProjectId }
    }
    
    // 根据类型刷新特定数据
    switch (type) {
      case 'outbound':
        const outboundResponse = await getProjectEquipmentOutboundList(params)
        outboundTableData.value = outboundResponse.records || []
        outboundCount.value = outboundTableData.value.length
        break
      case 'inbound':
        const inboundResponse = await getProjectEquipmentInboundList(params)
        inboundTableData.value = inboundResponse.records || []
        inboundCount.value = inboundTableData.value.length
        break
      case 'order':
        const orderResponse = await getProjectEquipmentOrderList(params)
        orderTableData.value = orderResponse.records || []
        orderCount.value = orderTableData.value.length
        break
      case 'contract':
        const contractResponse = await getProjectEquipmentManagementList(params)
        contractTableData.value = contractResponse.records || []
        contractCount.value = contractTableData.value.length
        break
    }
    
    // 重新生成库存汇总数据
    generateInventoryData(contractTableData.value, inboundTableData.value, outboundTableData.value)
    
    console.log(`${type} 数据已强制刷新`)
  } catch (error) {
    console.error(`强制刷新 ${type} 数据失败:`, error)
  }
}

// 导出数据
const exportData = () => {
  try {
    // 准备导出数据
    const exportData = {
      contracts: contractTableData.value,
      orders: orderTableData.value,
      inbounds: inboundTableData.value,
      outbounds: outboundTableData.value,
      inventory: inventoryTableData.value
    }
    
    // 创建CSV内容
    let csvContent = '设备材料管理数据导出\n\n'
    
    // 设备合同数据
    csvContent += '设备合同信息\n'
    csvContent += '编号,设备名称,设备型号,设备单位,设备数量,供货单位\n'
    exportData.contracts.forEach(item => {
      csvContent += `${item.id || ''},${item.equipment_name || ''},${item.equipment_type || ''},${item.equipment_sumtype || ''},${item.equipment_sum || ''},${item.supplier || ''}\n`
    })
    
    csvContent += '\n下单信息\n'
    csvContent += '编号,设备名称,下单数量,要求到货时间,采购人,备注\n'
    exportData.orders.forEach(item => {
      csvContent += `${item.id || ''},${item.equipment_name || ''},${item.quantity || ''},${item.Reqd_date || ''},${item.purchaser || ''},${item.remark || ''}\n`
    })
    
    csvContent += '\n入库信息\n'
    csvContent += '编号,设备名称,入库时间,入库数量,入库人员,备注\n'
    exportData.inbounds.forEach(item => {
      csvContent += `${item.id || ''},${item.equipment_name || ''},${item.in_date || ''},${item.quantity || ''},${item.receiver || ''},${item.remark || ''}\n`
    })
    
    csvContent += '\n出库信息\n'
    csvContent += '编号,设备名称,出库时间,出库数量,出库人员,出库地点,备注\n'
    exportData.outbounds.forEach(item => {
      csvContent += `${item.id || ''},${item.equipment_name || ''},${item.out_date || ''},${item.quantity || ''},${item.recipient || ''},${item.usage || ''},${item.remark || ''}\n`
    })
    
    csvContent += '\n库存汇总\n'
    csvContent += '设备名称,设备型号,合同数量,入库数量,出库数量,在库数量\n'
    exportData.inventory.forEach(item => {
      csvContent += `${item.equipment_name || ''},${item.equipment_type || ''},${item.total_quantity || ''},${item.inbound_quantity || ''},${item.outbound_quantity || ''},${item.in_stock_quantity || ''}\n`
    })
    
    // 创建下载链接
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `设备材料管理数据_${new Date().toISOString().split('T')[0]}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('数据导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('数据导出失败')
  }
}

// 统计数据计算
const getInStockCount = () => {
  return inventoryTableData.value.filter(item => item.in_stock_quantity > 0).length
}

const getOutOfStockCount = () => {
  return inventoryTableData.value.filter(item => item.in_stock_quantity === 0).length
}

const getLowStockCount = () => {
  return inventoryTableData.value.filter(item => item.in_stock_quantity < 0).length
}

const getEquipmentTypeStats = () => {
  const stats = {}
  inventoryTableData.value.forEach(item => {
    if (item.equipment_type) {
      stats[item.equipment_type] = (stats[item.equipment_type] || 0) + 1
    }
  })
  return stats
}

// 监听项目数据变化
watch(() => props.projectData, () => {
  if (props.projectData.project_id) {
    loadData()
  }
}, { immediate: true })

// 监听项目ID变化
watch(() => props.projectId, () => {
  if (props.projectId) {
    loadData()
  }
}, { immediate: true })

// 组件挂载时加载数据
onMounted(() => {
  if (props.projectData.project_id || props.projectId) {
    loadData()
  }
})

// 窗口大小变化时重新计算布局
const handleResize = () => {
  // 可以在这里添加响应式布局调整逻辑
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 业务逻辑约束判断函数
const canDeleteOrder = (order) => {
  // 如果有入库信息，则订单不能删除
  const hasInbound = inboundTableData.value.some(inbound => 
    inbound.equipment_id === order.equipment_id
  )
  return !hasInbound
}

const canDeleteInbound = (inbound) => {
  // 如果有出库信息，则入库不能删除
  const hasOutbound = outboundTableData.value.some(outbound => 
    outbound.equipment_id === inbound.equipment_id
  )
  return !hasOutbound
}

const canDeleteOutbound = (outbound) => {
  // 出库信息可以删除
  return true
}

// 验证入库数量不能超过订单数量
const validateInboundQuantity = (equipmentId, quantity) => {
  if (!equipmentId) {
    return { valid: false, message: '请选择关联设备' }
  }
  
  const order = orderTableData.value.find(o => o.equipment_id === equipmentId)
  if (!order) {
    return { valid: false, message: '未找到对应的订单信息，请先创建订单' }
  }
  
  if (quantity > order.quantity) {
    return { valid: false, message: `入库数量不能超过订单数量 ${order.quantity}` }
  }
  
  return { valid: true }
}

// 验证出库数量不能超过入库数量
const validateOutboundQuantity = (equipmentId, quantity) => {
  if (!equipmentId) {
    return { valid: false, message: '请选择关联设备' }
  }
  
  const inbound = inboundTableData.value.find(i => i.equipment_id === equipmentId)
  if (!inbound) {
    return { valid: false, message: '未找到对应的入库信息，请先创建入库记录' }
  }
  
  const totalOutbound = outboundTableData.value
    .filter(o => o.equipment_id === equipmentId)
    .reduce((sum, o) => sum + (o.quantity || 0), 0)
  
  const availableQuantity = inbound.quantity - totalOutbound
  
  if (quantity > availableQuantity) {
    return { valid: false, message: `出库数量不能超过可用库存数量 ${availableQuantity}` }
  }
  
  return { valid: true }
}

// 库存状态类型
const getStockStatusType = (row) => {
  // 根据设备名称查找库存信息
  const inventoryItem = inventoryTableData.value.find(item => item.equipment_name === row.equipment_name)
  if (!inventoryItem) return 'info'
  
  if (inventoryItem.in_stock_quantity > 0) return 'success'
  if (inventoryItem.in_stock_quantity === 0) return 'warning'
  return 'danger'
}

// 入库库存状态样式类
const getInboundStockStatusClass = (row) => {
  const quantity = getCurrentStockQuantity(row)
  if (quantity > 0) return 'stock-success'
  if (quantity === 0) return 'stock-warning'
  return 'stock-danger'
}

// 出库库存状态样式类
const getOutboundStockStatusClass = (row) => {
  const quantity = getCurrentStockQuantity(row)
  if (quantity > 0) return 'stock-success'
  if (quantity === 0) return 'stock-warning'
  return 'stock-danger'
}

// 库存汇总状态样式类
const getInventoryStockStatusClass = (row) => {
  if (row.in_stock_quantity > 0) return 'stock-success'
  if (row.in_stock_quantity === 0) return 'stock-warning'
  return 'stock-danger'
}

// 库存状态文本
const getStockStatusText = (row) => {
  // 根据设备名称查找库存信息
  const inventoryItem = inventoryTableData.value.find(item => item.equipment_name === row.equipment_name)
  if (!inventoryItem) return '未入库'
  
  if (inventoryItem.in_stock_quantity > 0) return '有库存'
  if (inventoryItem.in_stock_quantity === 0) return '无库存'
  return '库存不足'
}

// 获取库存不足的设备
const getLowStockItems = () => {
  return inventoryTableData.value.filter(item => item.in_stock_quantity < 0)
}

const handleAdvancedFilter = (command) => {
  // 在这里添加高级筛选逻辑
  console.log('高级筛选:', command)
}

// 入库状态类型
const getInboundStockStatusType = (row) => {
  // 根据设备名称查找库存信息
  const inventoryItem = inventoryTableData.value.find(item => item.equipment_name === row.equipment_name)
  if (!inventoryItem) return 'info'
  
  if (inventoryItem.in_stock_quantity > 0) return 'success'
  if (inventoryItem.in_stock_quantity === 0) return 'warning'
  return 'danger'
}

// 入库状态文本
const getInboundStockStatusText = (row) => {
  // 根据设备名称查找库存信息
  const inventoryItem = inventoryTableData.value.find(item => item.equipment_name === row.equipment_name)
  if (!inventoryItem) return '未入库'
  
  if (inventoryItem.in_stock_quantity > 0) return '有库存'
  if (inventoryItem.in_stock_quantity === 0) return '无库存'
  return '库存不足'
}

// 出库状态类型
const getOutboundStockStatusType = (row) => {
  // 根据设备名称查找库存信息
  const inventoryItem = inventoryTableData.value.find(item => item.equipment_name === row.equipment_name)
  if (!inventoryItem) return 'info'
  
  if (inventoryItem.in_stock_quantity > 0) return 'success'
  if (inventoryItem.in_stock_quantity === 0) return 'warning'
  return 'danger'
}

// 出库状态文本
const getOutboundStockStatusText = (row) => {
  // 根据设备名称查找库存信息
  const inventoryItem = inventoryTableData.value.find(item => item.equipment_name === row.equipment_name)
  if (!inventoryItem) return '未入库'
  
  if (inventoryItem.in_stock_quantity > 0) return '有库存'
  if (inventoryItem.in_stock_quantity === 0) return '无库存'
  return '库存不足'
}

// 库存状态类型
const getInventoryStockStatusType = (row) => {
  // 根据设备名称查找库存信息
  const inventoryItem = inventoryTableData.value.find(item => item.equipment_name === row.equipment_name)
  if (!inventoryItem) return 'info'
  
  if (inventoryItem.in_stock_quantity > 0) return 'success'
  if (inventoryItem.in_stock_quantity === 0) return 'warning'
  return 'danger'
}

// 库存状态文本
const getInventoryStockStatusText = (row) => {
  // 根据设备名称查找库存信息
  const inventoryItem = inventoryTableData.value.find(item => item.equipment_name === row.equipment_name)
  if (!inventoryItem) return '未入库'
  
  if (inventoryItem.in_stock_quantity > 0) return '有库存'
  if (inventoryItem.in_stock_quantity === 0) return '无库存'
  return '库存不足'
}

// 获取当前库存数量
const getCurrentStockQuantity = (row) => {
  const inventoryItem = inventoryTableData.value.find(item => 
    item.equipment_name === row.equipment_name
  )
  return inventoryItem ? inventoryItem.in_stock_quantity : 0
}

// 操作建议
const getOperationSuggestion = (row) => {
  if (row.in_stock_quantity > 0) {
    return '库存充足，无需补充'
  } else if (row.in_stock_quantity === 0) {
    return '库存不足需要采购'
  } else {
    return '库存异常，请检查'
  }
}

// 改进设备选择逻辑 - 确保设备列表正确加载
const loadEquipmentList = async () => {
  try {
    const currentProjectId = props.projectData.project_id || props.projectId
    if (!currentProjectId) return
    
    const params = {
      page: 1,
      pageSize: 1000, // 获取所有设备
      where: { project_id: currentProjectId }
    }
    
    const response = await getProjectEquipmentManagementList(params)
    const equipmentData = response.records || []
    
    // 确保设备列表包含必要的字段
    equipmentList.value = equipmentData.map(equipment => ({
      id: equipment.id,
      equipment_name: equipment.equipment_name,
      equipment_type: equipment.equipment_type,
      equipment_sumtype: equipment.equipment_sumtype,
      equipment_sum: equipment.equipment_sum,
      supplier: equipment.supplier
    }))
  } catch (error) {
    console.error('加载设备列表失败:', error)
    ElMessage.error('加载设备列表失败')
  }
}

// 设备选择变化时的处理
const handleEquipmentChange = (equipmentId) => {
  if (!equipmentId) return
  
  const selectedEquipment = equipmentList.value.find(e => e.id === equipmentId)
  if (selectedEquipment) {
    // 根据选择的设备自动填充相关信息
    if (currentDialogType.value === 'order') {
      // 下单时，可以显示设备的合同信息
      const contract = contractTableData.value.find(c => c.id === equipmentId)
      if (contract) {
        // 计算该设备已有的累计订单数量
        const existingOrders = orderTableData.value.filter(o => o.equipment_id === equipmentId)
        const totalOrderedQuantity = existingOrders.reduce((sum, order) => sum + (Number(order.quantity) || 0), 0)
        const remainingQuantity = contract.equipment_sum - totalOrderedQuantity
        
        ElMessage.info(`已选择设备: ${selectedEquipment.equipment_name}，合同数量: ${contract.equipment_sum}，已下单: ${totalOrderedQuantity}，剩余可下单: ${remainingQuantity}`)
        
        // 如果剩余数量不足，给出警告
        if (remainingQuantity <= 0) {
          ElMessage.warning(`该设备的累计订单数量已超过合同数量，建议修改合同数量`)
        }
      }
    } else if (currentDialogType.value === 'inbound') {
      // 入库时，检查订单信息
      const orders = orderTableData.value.filter(o => o.equipment_id === equipmentId)
      if (orders.length > 0) {
        // 计算该设备所有订单的总数量
        const totalOrderQuantity = orders.reduce((sum, order) => sum + (Number(order.quantity) || 0), 0)
        
        // 计算该设备已经入库的总数量
        const existingInbounds = inboundTableData.value.filter(i => i.equipment_id === equipmentId)
        const totalInboundQuantity = existingInbounds.reduce((sum, inbound) => sum + (Number(inbound.quantity) || 0), 0)
        
        const remainingQuantity = totalOrderQuantity - totalInboundQuantity
        
        ElMessage.info(`已选择设备: ${selectedEquipment.equipment_name}，订单总数量: ${totalOrderQuantity}，已入库: ${totalInboundQuantity}，剩余可入库: ${remainingQuantity}`)
        
        // 如果剩余数量不足，给出警告
        if (remainingQuantity <= 0) {
          ElMessage.warning(`该设备的累计入库数量已超过订单总数量，请先新增订单`)
        }
      } else {
        ElMessage.warning(`该设备没有对应的订单，请先创建订单信息`)
      }
    } else if (currentDialogType.value === 'outbound') {
      // 出库时，检查库存信息
      const inventoryItem = inventoryTableData.value.find(item => 
        item.equipment_name === selectedEquipment.equipment_name
      )
      if (inventoryItem) {
        if (inventoryItem.in_stock_quantity > 0) {
          ElMessage.info(`已选择设备: ${selectedEquipment.equipment_name}，当前库存: ${inventoryItem.in_stock_quantity}`)
        } else {
          ElMessage.warning(`该设备库存不足，当前库存: ${inventoryItem.in_stock_quantity}，请先新增入库信息`)
        }
      } else {
        ElMessage.warning(`该设备没有库存信息，请先创建入库信息`)
      }
    }
  }
}

// 获取设备的详细信息（用于显示和验证）
const getEquipmentInfo = (equipmentId) => {
  return equipmentList.value.find(e => e.id === equipmentId)
}

// 获取设备的库存信息
const getEquipmentInventory = (equipmentId) => {
  const equipment = getEquipmentInfo(equipmentId)
  if (!equipment) return null
  
  return inventoryTableData.value.find(item => 
    item.equipment_name === equipment.equipment_name
  )
}

// 验证设备操作的业务逻辑
const validateEquipmentOperation = (type, equipmentId, quantity) => {
  const equipment = getEquipmentInfo(equipmentId)
  if (!equipment) {
    return { valid: false, message: '设备不存在' }
  }
  
  switch (type) {
    case 'order':
      // 编辑模式下，主要检查订单数量是否不小于出库数量
      if (currentRow.value && currentRow.value.id) {
        // 编辑模式：计算其他订单记录的总数量
        const otherOrders = orderTableData.value.filter(o => 
          o.equipment_id === equipmentId && o.id !== currentRow.value.id
        )
        const otherOrderQuantity = otherOrders.reduce((sum, o) => sum + (Number(o.quantity) || 0), 0)
        
        // 计算该设备所有出库记录的总数量
        const outbounds = outboundTableData.value.filter(o => o.equipment_id === equipmentId)
        const totalOutboundQuantity = outbounds.reduce((sum, outbound) => sum + (Number(outbound.quantity) || 0), 0)
        
        // 新的总订单数量不能小于出库数量
        if (otherOrderQuantity + quantity < totalOutboundQuantity) {
          const minRequiredQuantity = totalOutboundQuantity - otherOrderQuantity
          return { 
            valid: false, 
            message: `订单数量调整后，总订单数量 ${otherOrderQuantity + quantity} 将小于出库数量 ${totalOutboundQuantity}。最小需要调整为: ${minRequiredQuantity}` 
          }
        }
      } else {
        // 新增模式：检查设备是否有合同
        const contract = contractTableData.value.find(c => c.id === equipmentId)
        if (!contract) {
          return { valid: false, message: '该设备没有合同信息' }
        }
        
        // 计算该设备已有的累计订单数量
        const existingOrders = orderTableData.value.filter(o => o.equipment_id === equipmentId)
        const totalOrderedQuantity = existingOrders.reduce((sum, order) => sum + (Number(order.quantity) || 0), 0)
        
        // 检查新增订单数量加上已有订单数量是否超过合同数量
        if (totalOrderedQuantity + quantity > contract.equipment_sum) {
          const remainingQuantity = contract.equipment_sum - totalOrderedQuantity
          if (remainingQuantity <= 0) {
            return { 
              valid: false, 
              message: `该设备的累计订单数量 ${totalOrderedQuantity} 已超过合同数量 ${contract.equipment_sum}，请先修改合同数量或删除多余订单` 
            }
          } else {
            return { 
              valid: false, 
              message: `该设备的累计订单数量 ${totalOrderedQuantity}，新增 ${quantity} 后将超过合同数量 ${contract.equipment_sum}。建议修改合同数量为 ${totalOrderedQuantity + quantity}，或减少下单数量至 ${remainingQuantity}` 
            }
          }
        }
      }
      break
      
    case 'inbound':
      // 编辑模式下，检查入库数量不能超过订单总数量，也不能低于出库总数量
      if (currentRow.value && currentRow.value.id) {
        // 编辑模式：计算其他入库记录的总数量
        const otherInbounds = inboundTableData.value.filter(i => 
          i.equipment_id === equipmentId && i.id !== currentRow.value.id
        )
        const otherInboundQuantity = otherInbounds.reduce((sum, i) => sum + (Number(i.quantity) || 0), 0)
        
        // 计算该设备所有出库记录的总数量
        const outbounds = outboundTableData.value.filter(o => o.equipment_id === equipmentId)
        const totalOutboundQuantity = outbounds.reduce((sum, outbound) => sum + (Number(outbound.quantity) || 0), 0)
        
        // 计算该设备所有订单的总数量
        const orders = orderTableData.value.filter(o => o.equipment_id === equipmentId)
        const totalOrderQuantity = orders.reduce((sum, order) => sum + (Number(order.quantity) || 0), 0)
        
        // 新的总入库数量不能小于出库数量
        if (otherInboundQuantity + quantity < totalOutboundQuantity) {
          const minRequiredQuantity = totalOutboundQuantity - otherInboundQuantity
          return { 
            valid: false, 
            message: `入库数量调整后，总入库数量 ${otherInboundQuantity + quantity} 将小于出库数量 ${totalOutboundQuantity}。最小需要调整为: ${minRequiredQuantity}` 
          }
        }
        
        // 新的总入库数量不能超过订单总数量
        if (otherInboundQuantity + quantity > totalOrderQuantity) {
          const maxAllowedQuantity = totalOrderQuantity - otherInboundQuantity
          return { 
            valid: false, 
            message: `入库数量调整后，总入库数量 ${otherInboundQuantity + quantity} 将超过订单总数量 ${totalOrderQuantity}。最大可调整为: ${maxAllowedQuantity}` 
          }
        }
      } else {
        // 新增模式：检查是否有对应订单
        const orders = orderTableData.value.filter(o => o.equipment_id === equipmentId)
        if (orders.length === 0) {
          return { valid: false, message: '该设备没有对应的订单，请先创建订单信息' }
        }
        
        // 计算该设备所有订单的总数量
        const totalOrderQuantity = orders.reduce((sum, order) => sum + (Number(order.quantity) || 0), 0)
        
        // 计算该设备已经入库的总数量
        const existingInbounds = inboundTableData.value.filter(i => i.equipment_id === equipmentId)
        const totalInboundQuantity = existingInbounds.reduce((sum, inbound) => sum + (Number(inbound.quantity) || 0), 0)
        
        // 检查新增入库数量加上已入库数量是否超过订单总数量
        if (totalInboundQuantity + quantity > totalOrderQuantity) {
          const remainingQuantity = totalOrderQuantity - totalInboundQuantity
          if (remainingQuantity <= 0) {
            return { 
              valid: false, 
              message: `该设备的累计入库数量 ${totalInboundQuantity} 已达到订单总数量 ${totalOrderQuantity}，请先新增订单` 
            }
          } else {
            return { 
              valid: false, 
              message: `该设备的累计入库数量 ${totalInboundQuantity}，新增 ${quantity} 后将超过订单总数量 ${totalOrderQuantity}。建议减少入库数量至 ${remainingQuantity}` 
            }
          }
        }
        
        // 检查入库数量是否不小于出库数量
        const outbounds = outboundTableData.value.filter(o => o.equipment_id === equipmentId)
        const totalOutboundQuantity = outbounds.reduce((sum, outbound) => sum + (Number(outbound.quantity) || 0), 0)
        
        if (totalInboundQuantity + quantity < totalOutboundQuantity) {
          return { 
            valid: false, 
            message: `入库数量 ${totalInboundQuantity + quantity} 小于出库数量 ${totalOutboundQuantity}，请确保入库数量不小于出库数量` 
          }
        }
      }
      
      break
      
    case 'outbound':
      // 检查库存是否充足
      const inventory = getEquipmentInventory(equipmentId)
      if (!inventory) {
        return { valid: false, message: '该设备没有库存信息，请先创建入库信息' }
      }
      
      // 编辑模式下，检查数量调整是否合理
      if (currentRow.value && currentRow.value.id) {
        // 编辑模式：计算其他出库记录的总数量
        const otherOutbounds = outboundTableData.value.filter(o => 
          o.equipment_id === equipmentId && o.id !== currentRow.value.id
        )
        const otherOutboundQuantity = otherOutbounds.reduce((sum, o) => sum + (Number(o.quantity) || 0), 0)
        
        // 新的总出库数量不能超过入库数量
        if (otherOutboundQuantity + quantity > inventory.inbound_quantity) {
          const maxAllowedQuantity = inventory.inbound_quantity - otherOutboundQuantity
          return { 
            valid: false, 
            message: `出库数量调整后，总出库数量 ${otherOutboundQuantity + quantity} 将超过入库数量 ${inventory.inbound_quantity}。最大可调整为: ${maxAllowedQuantity}` 
          }
        }
      } else {
        // 新增模式：直接检查是否超过库存
        if (quantity > inventory.in_stock_quantity) {
          return { valid: false, message: `出库数量不能超过当前库存 ${inventory.in_stock_quantity}，请先新增入库信息` }
        }
      }
      break
  }
  
  return { valid: true }
}

// 验证设备是否已存在（用于新增设备合同时）
const validateEquipmentExists = (equipmentName, equipmentType, currentId = null) => {
  if (!equipmentName || !equipmentType) return { valid: true }
  
  // 编辑模式下，排除当前编辑的记录
  const exists = contractTableData.value.some(contract => 
    contract.equipment_name === equipmentName && 
    contract.equipment_type === equipmentType &&
    contract.id !== currentId // 排除当前编辑的记录
  )
  
  if (exists) {
    return { 
      valid: false, 
      message: '该设备名称和型号已存在，请使用不同的名称或型号' 
    }
  }
  
  return { valid: true }
}

// 改进表单验证规则，添加设备关联验证
const getFormRules = () => {
  const baseRules = {
    project_id: [{ required: true, message: '请输入项目编号', trigger: 'blur' }]
  }
  
  switch (currentDialogType.value) {
    case 'contract':
      return {
        ...baseRules,
        equipment_name: [
          { required: true, message: '请输入设备名称', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              if (value && currentDialogType.value === 'contract') {
                // 编辑模式下传递当前记录ID，新增模式下传递null
                const currentId = currentRow.value?.id || null
                const validation = validateEquipmentExists(value, formData.equipment_type, currentId)
                if (!validation.valid) {
                  callback(new Error(validation.message))
                } else {
                  callback()
                }
              } else {
                callback()
              }
            }, 
            trigger: 'blur' 
          }
        ],
        equipment_type: [{ required: true, message: '请输入设备型号', trigger: 'blur' }],
        equipment_sum: [{ required: true, message: '请输入设备数量', trigger: 'blur' }],
        supplier: [{ required: true, message: '请输入供货单位', trigger: 'blur' }]
      }
    case 'order':
      return {
        ...baseRules,
        equipment_id: [
          { required: true, message: '请选择设备', trigger: 'change' },
          { 
            validator: (rule, value, callback) => {
              if (value) {
                const equipment = equipmentList.value.find(e => e.id === value)
                if (!equipment) {
                  callback(new Error('选择的设备不存在'))
                } else {
                  callback()
                }
              } else {
                callback()
              }
            }, 
            trigger: 'change' 
          }
        ],
        quantity: [{ required: true, message: '请输入下单数量', trigger: 'blur' }],
        Reqd_date: [{ required: true, message: '请选择要求到货时间', trigger: 'change' }],
        purchaser: [{ required: true, message: '请输入采购人', trigger: 'blur' }]
      }
    case 'inbound':
      return {
        ...baseRules,
        equipment_id: [
          { required: true, message: '请选择设备', trigger: 'change' },
          { 
            validator: (rule, value, callback) => {
              if (value) {
                const equipment = equipmentList.value.find(e => e.id === value)
                if (!equipment) {
                  callback(new Error('选择的设备不存在'))
                } else {
                  // 编辑模式下不检查订单数量限制，只检查是否有对应订单
                  if (currentRow.value && currentRow.value.id) {
                    const orders = orderTableData.value.filter(o => o.equipment_id === value)
                    if (orders.length === 0) {
                      callback(new Error('该设备没有对应的订单，请先创建订单信息'))
                    } else {
                      callback()
                    }
                  } else {
                    // 新增模式：检查是否有对应的订单
                    const orders = orderTableData.value.filter(o => o.equipment_id === value)
                    if (orders.length === 0) {
                      callback(new Error('该设备没有对应的订单，请先创建订单信息'))
                    } else {
                      // 检查累计入库数量是否超过订单总数量
                      const totalOrderQuantity = orders.reduce((sum, order) => sum + (Number(order.quantity) || 0), 0)
                      const existingInbounds = inboundTableData.value.filter(i => i.equipment_id === value)
                      const totalInboundQuantity = existingInbounds.reduce((sum, inbound) => sum + (Number(inbound.quantity) || 0), 0)
                      
                      if (totalInboundQuantity >= totalOrderQuantity) {
                        callback(new Error(`该设备的累计入库数量 ${totalInboundQuantity} 已达到订单总数量 ${totalOrderQuantity}，请先新增订单`))
                      } else {
                        callback()
                      }
                    }
                  }
                }
              } else {
                callback()
              }
            }, 
            trigger: 'change' 
          }
        ],
        quantity: [{ required: true, message: '请输入入库数量', trigger: 'blur' }],
        in_date: [{ required: true, message: '请选择入库时间', trigger: 'change' }],
        receiver: [{ required: true, message: '请输入入库人员', trigger: 'blur' }]
      }
    case 'outbound':
      return {
        ...baseRules,
        equipment_id: [
          { required: true, message: '请选择设备', trigger: 'change' },
          { 
            validator: (rule, value, callback) => {
              if (value) {
                const equipment = equipmentList.value.find(e => e.id === value)
                if (!equipment) {
                  callback(new Error('选择的设备不存在'))
                } else {
                  // 检查是否有对应的入库记录
                  const hasInbound = inboundTableData.value.some(i => i.equipment_id === value)
                  if (!hasInbound) {
                    callback(new Error('该设备没有对应的入库记录，请先创建入库信息'))
                  } else {
                    // 检查库存是否充足
                    const inventoryItem = inventoryTableData.value.find(item => 
                      item.equipment_name === equipment.equipment_name
                    )
                    if (inventoryItem && inventoryItem.in_stock_quantity <= 0) {
                      callback(new Error('该设备库存不足，请先新增入库信息'))
                    } else {
                      callback()
                    }
                  }
                }
              } else {
                callback()
              }
            }, 
            trigger: 'change' 
          }
        ],
        quantity: [{ required: true, message: '请输入出库数量', trigger: 'blur' }],
        out_date: [{ required: true, message: '请选择出库时间', trigger: 'change' }],
        shipper: [{ required: true, message: '请输入出库人员', trigger: 'blur' }]
      }
    default:
      return baseRules
  }
}

// 获取设备合同信息
const getEquipmentContractInfo = (equipmentId) => {
  const contract = contractTableData.value.find(c => c.id === equipmentId)
  return contract ? true : false
}

// 获取设备订单信息
const getEquipmentOrderInfo = (equipmentId) => {
  const order = orderTableData.value.find(o => o.equipment_id === equipmentId)
  return order ? true : false
}

// 时间格式转换函数 - 将UTC时间转换为中国时间，格式为 YYYY-MM-DD
const formatToChinaTime = (dateString) => {
  if (!dateString) return ''
  
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return dateString
    
    // 转换为中国时间（UTC+8）
    const chinaTime = new Date(date.getTime() + 8 * 60 * 60 * 1000)
    
    // 格式化为 YYYY-MM-DD
    const year = chinaTime.getUTCFullYear()
    const month = String(chinaTime.getUTCMonth() + 1).padStart(2, '0')
    const day = String(chinaTime.getUTCDate()).padStart(2, '0')
    
    return `${year}-${month}-${day}`
  } catch (error) {
    console.error('时间转换错误:', error)
    return dateString
  }
}

// 获取设备的完整关联信息
const getEquipmentFullInfo = (equipmentId) => {
  const equipment = getEquipmentInfo(equipmentId)
  if (!equipment) return null
  
  const contract = contractTableData.value.find(c => c.id === equipmentId)
  const order = orderTableData.value.find(o => o.equipment_id === equipmentId)
  const inbound = inboundTableData.value.find(i => i.equipment_id === equipmentId)
  const outbound = outboundTableData.value.find(o => o.equipment_id === equipmentId)
  const inventory = getEquipmentInventory(equipmentId)
  
  return {
    equipment,
    contract,
    order,
    inbound,
    outbound,
    inventory
  }
}

// 显示设备的关联信息详情
const showEquipmentDetails = (equipmentId) => {
  const fullInfo = getEquipmentFullInfo(equipmentId)
  if (!fullInfo) {
    ElMessage.warning('设备信息不存在')
    return
  }
  
  const { equipment, contract, order, inbound, outbound, inventory } = fullInfo
  
  let message = `设备: ${equipment.equipment_name}\n`
  message += `型号: ${equipment.equipment_type}\n`
  
  if (contract) {
    message += `合同数量: ${contract.equipment_sum}\n`
  }
  
  if (order) {
    message += `订单数量: ${order.quantity}\n`
  }
  
  if (inbound) {
    message += `入库数量: ${inbound.quantity}\n`
  }
  
  if (outbound) {
    message += `出库数量: ${outbound.quantity}\n`
  }
  
  if (inventory) {
    message += `当前库存: ${inventory.in_stock_quantity}\n`
  }
  
  ElMessageBox.alert(message, '设备详细信息', {
    confirmButtonText: '确定',
    type: 'info'
  })
}

// 检查设备操作的完整性
const checkEquipmentOperationIntegrity = (equipmentId) => {
  const fullInfo = getEquipmentFullInfo(equipmentId)
  if (!fullInfo) return { valid: false, message: '设备不存在' }
  
  const { contract, order, inbound, outbound } = fullInfo
  const issues = []
  
  if (!contract) {
    issues.push('缺少设备合同')
  }
  
  if (!order) {
    issues.push('缺少订单信息')
  }
  
  if (!inbound) {
    issues.push('缺少入库记录')
  }
  
  if (issues.length > 0) {
    return {
      valid: false,
      message: `设备操作不完整: ${issues.join(', ')}`,
      issues
    }
  }
  
  return { valid: true }
}

  

  

</script>

<style scoped>
.equipment-management {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

/* 页面头部样式 */
.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  color: white;
}

.page-header h2 {
  margin: 0;
  font-size: 28px;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.header-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.create-btn {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.create-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
}

/* 项目信息卡片 */
.project-info {
  margin-bottom: 24px;
}

.info-card {
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
}

.info-content {
  padding: 8px 0;
}

.project-title {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
}

.title-icon {
  margin-right: 8px;
  color: #409EFF;
}

.project-desc {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

/* 搜索区域样式 */
.search-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  min-width: 300px;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 概览卡片样式 */
.overview-cards {
  margin-bottom: 24px;
}

.overview-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;
  height: 100%;
}

.overview-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  color: white;
}

.contract-card .card-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.order-card .card-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.inbound-card .card-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.outbound-card .card-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-content {
  flex: 1;
}

.card-number {
  font-size: 32px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.card-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

/* 数据统计图表样式 */
.statistics-section {
  margin-bottom: 24px;
}

.chart-card {
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
}

.chart-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.chart-container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 20px;
  gap: 20px;
  flex-wrap: wrap;
}

.stat-item {
  text-align: center;
  flex: 1;
  min-width: 150px;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 8px;
}

.stat-number.success {
  color: #67c23a;
}

.stat-number.danger {
  color: #f56c6c;
}

.stat-number.warning {
  color: #e6a23c;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.type-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
}

.type-stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #f0f2ff;
  border-radius: 8px;
  padding: 8px 12px;
  font-size: 14px;
  color: #409EFF;
  font-weight: 500;
}

.type-name {
  white-space: nowrap;
}

.type-count {
  background: #e1f3d8;
  color: #67c23a;
  padding: 4px 8px;
  border-radius: 6px;
  font-weight: 600;
}

/* 表格容器样式 */
.tables-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
}

.table-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-title .el-icon {
  color: #409EFF;
  font-size: 20px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-table .el-table__header) {
  background: #f5f7fa;
  color: #303133;
}

:deep(.el-table .el-table__header th) {
  background: #f5f7fa;
  color: #303133;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
  padding: 12px 0;
}

:deep(.el-table .el-table__header th .cell) {
  color: #303133;
  font-weight: 600;
}

:deep(.el-table .el-table__header-wrapper) {
  background: #f5f7fa;
}

:deep(.el-table .el-table__body-wrapper) {
  background: white;
}

:deep(.el-table .el-table__row:nth-child(even)) {
  background: #fafafa;
}

:deep(.el-table .el-table__row:nth-child(odd)) {
  background: white;
}

:deep(.el-table .el-table__row:hover) {
  background: linear-gradient(135deg, #f0f2ff 0%, #e8f4fd 100%);
  transform: scale(1.01);
  transition: all 0.3s ease;
}

:deep(.el-table .el-table__row) {
  transition: all 0.3s ease;
}

:deep(.el-table .el-table__cell) {
  border-bottom: 1px solid #f0f0f0;
  padding: 12px 0;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 表单区域样式 */
.form-section {
  margin-bottom: 24px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409EFF;
}

.form-section h3 {
  margin: 0 0 20px 0;
  color: #409EFF;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.form-section h3::before {
  content: '';
  width: 4px;
  height: 18px;
  background: #409EFF;
  margin-right: 12px;
  border-radius: 2px;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 24px;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  background: #f8f9fa;
  border-top: 1px solid #e4e7ed;
}

/* 详情内容样式 */
.detail-content {
  padding: 20px;
}

:deep(.el-descriptions) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 6px;
  font-weight: 500;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .equipment-management {
    padding: 16px;
  }
  
  .page-header {
    padding: 20px;
  }
  
  .page-header h2 {
    font-size: 24px;
  }
  
  .header-actions {
    gap: 8px;
  }
  
  .create-btn {
    padding: 8px 16px;
    font-size: 14px;
  }
  
  .overview-card {
    padding: 20px;
  }
  
  .card-number {
    font-size: 28px;
  }
}

@media (max-width: 1200px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-actions {
    justify-content: flex-start;
  }
  
  .search-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    min-width: auto;
  }
  
  .overview-cards .el-col {
    margin-bottom: 16px;
  }
  
  .tables-container {
    gap: 20px;
  }
}

@media (max-width: 768px) {
  .equipment-management {
    padding: 12px;
  }
  
  .page-header {
    padding: 16px;
    margin-bottom: 16px;
  }
  
  .page-header h2 {
    font-size: 20px;
  }
  
  .header-actions {
    flex-direction: column;
    width: 100%;
  }
  
  .create-btn {
    width: 100%;
    justify-content: center;
  }
  
  .search-section {
    padding: 16px;
    margin-bottom: 16px;
  }
  
  .overview-cards {
    margin-bottom: 16px;
  }
  
  .overview-card {
    padding: 16px;
  }
  
  .card-icon {
    width: 50px;
    height: 50px;
    font-size: 24px;
  }
  
  .card-number {
    font-size: 24px;
  }
  
  .tables-container {
    gap: 16px;
  }
  
  .table-card {
    margin-bottom: 16px;
  }
  
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }
  
  :deep(.el-dialog__body) {
    padding: 16px;
  }
  
  .dialog-footer {
    padding: 16px;
  }
}

@media (max-width: 480px) {
  .equipment-management {
    padding: 8px;
  }
  
  .page-header {
    padding: 12px;
  }
  
  .page-header h2 {
    font-size: 18px;
  }
  
  .search-section {
    padding: 12px;
  }
  
  .overview-cards {
    margin-bottom: 12px;
  }
  
  .overview-card {
    padding: 12px;
  }
  
  .card-icon {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }
  
  .card-number {
    font-size: 20px;
  }
  
  .tables-container {
    gap: 12px;
  }
}

/* 表格列自适应 */
@media (max-width: 1400px) {
  :deep(.el-table .el-table__cell) {
    padding: 8px 4px;
  }
  
  :deep(.el-table .el-table__header th) {
    padding: 12px 4px;
  }
}

@media (max-width: 1200px) {
  :deep(.el-table .el-table__cell) {
    padding: 6px 2px;
    font-size: 13px;
  }
  
  :deep(.el-table .el-table__header th) {
    padding: 10px 2px;
    font-size: 13px;
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.equipment-management {
  animation: fadeInUp 0.6s ease-out;
}

/* 滚动条美化 */
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}

/* 库存预警信息样式 */
.warning-card {
  border-left: 4px solid #e6a23c;
}

.warning-list {
  padding: 16px;
}

.warning-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.warning-text {
  font-size: 14px;
  color: #606266;
}

.no-warning {
  font-size: 14px;
  color: #909399;
}

/* 操作建议样式 */
.operation-suggestion {
  font-size: 13px;
  color: #606266;
  padding: 4px 8px;
  background: #f0f9ff;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

/* 库存状态样式 */
.stock-success {
  color: #67c23a;
  font-weight: 600;
  font-size: 14px;
}

.stock-warning {
  color: #e6a23c;
  font-weight: 600;
  font-size: 14px;
}

.stock-danger {
  color: #f56c6c;
  font-weight: 600;
  font-size: 14px;
}
</style> 
